package jp.oesf.rssreader;

import jp.oesf.rssreader.model.RowModel;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
 
public class CategoryChoice extends ListActivity {

	private TableAdapter adapter = null;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.summary);

        adapter = new TableAdapter(this);
        setListAdapter(adapter);
        //TableAdapterにRowModelを設定する
        setRowModel(adapter);
	}

	private void setRowModel(TableAdapter adapter) {
		//画面に表示する一覧の１行を生成していきます。
		
		//DBの読み込み準備
        RssSQLiteOpenHelper databaseOpenHelper = new RssSQLiteOpenHelper(this);
        SQLiteDatabase database = databaseOpenHelper.getReadableDatabase();
 
        //カテゴリの重複をなくして検索する（"category"の昇順）
        Cursor cursor = database.query(RssSQLiteOpenHelper.RSS_TABLE,null,null,null,"category",null,"category");
               
        //テーブル１件毎にRowModelを作成し、TableAdapterに追加する
        while (cursor.moveToNext()) {
        	//if(category != cursor.getString(cursor.getColumnIndex("category")))
        	RowModel row = new RowModel();
            row.setId(cursor.getLong(cursor.getColumnIndex("_id")));
            row.setCategory(cursor.getString(cursor.getColumnIndex("category")));
        	adapter.add(row);
        }
        databaseOpenHelper.close();
	}
		
	public class TableAdapter extends ArrayAdapter<RowModel> {

		public TableAdapter(Context context) {
			super(context,R.layout.summary);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			RowModel item = getItem(position);
			if (row == null) {
				//Viewを作成する
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.catsummary_row, null);
			}
			if ( item!= null) {
				// Title
				TextView textTitle = (TextView)row.findViewById(R.id.summary_title);
				if (textTitle != null) {
					textTitle.setText(item.getCategory());
				}
			}
			return row;
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
 		
		Intent intent = new Intent(this, SummaryList.class);
		//選択された1行の情報を取得
		RowModel row = adapter.getItem(position);
		//カテゴリ名をパラメタとして設定
		intent.putExtra("category", row.getCategory());
		//SummaryListへ遷移
		startActivity(intent);
	}
}